import 'dart:io';
import 'package:excel/excel.dart';
import 'package:pdf/pdf.dart';
import 'package:pdf/widgets.dart' as pw;
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:share_plus/share_plus.dart';
import 'package:flutter/services.dart';

class ExportService {
  static final ExportService _instance = ExportService._internal();
  factory ExportService() => _instance;
  ExportService._internal();

  /// 请求存储权限
  Future<bool> requestStoragePermission() async {
    if (Platform.isAndroid) {
      final status = await Permission.storage.request();
      return status.isGranted;
    }
    return true;
  }

  /// 获取导出目录
  Future<String> getExportDirectory() async {
    if (Platform.isAndroid) {
      final directory = await getExternalStorageDirectory();
      final exportDir = Directory('${directory!.path}/RemberCount/Exports');
      if (!await exportDir.exists()) {
        await exportDir.create(recursive: true);
      }
      return exportDir.path;
    } else {
      // iOS使用临时目录
      final directory = await getTemporaryDirectory();
      final exportDir = Directory('${directory.path}/RemberCount/Exports');
      if (!await exportDir.exists()) {
        await exportDir.create(recursive: true);
      }
      return exportDir.path;
    }
  }

  /// 分享文件
  Future<void> shareFile(String filePath, String title) async {
    try {
      final file = XFile(filePath);
      await Share.shareXFiles(
        [file],
        text: title,
        subject: title,
      );
    } catch (e) {
      print('分享文件失败: $e');
      Get.snackbar('错误', '分享文件失败: $e');
    }
  }

  /// 导出为PDF
  Future<String?> exportToPDF(List<Map<String, dynamic>> data, String type, String period) async {
    try {
      if (!await requestStoragePermission()) {
        Get.snackbar('错误', '需要存储权限才能导出文件');
        return null;
      }

      final pdf = pw.Document();
      final exportDir = await getExportDirectory();
      final fileName = '${type}_${period}_${DateTime.now().millisecondsSinceEpoch}.pdf';

      // 添加标题
      pdf.addPage(
        pw.MultiPage(
          pageFormat: PdfPageFormat.a4,
          theme: pw.ThemeData.withFont(
            base: pw.Font.helvetica(),
            bold: pw.Font.helveticaBold(),
          ),
          build: (context) => [
            pw.Header(
              level: 0,
              child: pw.Text(
                '$type报表 - $period',
                style: pw.TextStyle(
                  fontSize: 24,
                  fontWeight: pw.FontWeight.bold,
                ),
              ),
            ),
            pw.SizedBox(height: 20),
            // 添加数据表格
            pw.Table(
              border: pw.TableBorder.all(color: PdfColors.grey),
              children: [
                // 表头
                pw.TableRow(
                  decoration: const pw.BoxDecoration(color: PdfColors.blue),
                  children: [
                    pw.Padding(
                      padding: const pw.EdgeInsets.all(8),
                      child: pw.Text(
                        '分类',
                        style: pw.TextStyle(
                          color: PdfColors.white,
                          fontWeight: pw.FontWeight.bold,
                        ),
                      ),
                    ),
                    pw.Padding(
                      padding: const pw.EdgeInsets.all(8),
                      child: pw.Text(
                        '金额',
                        style: pw.TextStyle(
                          color: PdfColors.white,
                          fontWeight: pw.FontWeight.bold,
                        ),
                        textAlign: pw.TextAlign.right,
                      ),
                    ),
                    pw.Padding(
                      padding: const pw.EdgeInsets.all(8),
                      child: pw.Text(
                        '占比',
                        style: pw.TextStyle(
                          color: PdfColors.white,
                          fontWeight: pw.FontWeight.bold,
                        ),
                        textAlign: pw.TextAlign.right,
                      ),
                    ),
                  ],
                ),
                // 数据行
                ...data.map((item) => pw.TableRow(
                  children: [
                    pw.Padding(
                      padding: const pw.EdgeInsets.all(8),
                      child: pw.Text(
                        item['name'],
                        style: const pw.TextStyle(fontSize: 12),
                      ),
                    ),
                    pw.Padding(
                      padding: const pw.EdgeInsets.all(8),
                      child: pw.Text(
                        '¥${item['amount'].toStringAsFixed(2)}',
                        style: const pw.TextStyle(fontSize: 12),
                        textAlign: pw.TextAlign.right,
                      ),
                    ),
                    pw.Padding(
                      padding: const pw.EdgeInsets.all(8),
                      child: pw.Text(
                        '${item['percent'].toStringAsFixed(1)}%',
                        style: const pw.TextStyle(fontSize: 12),
                        textAlign: pw.TextAlign.right,
                      ),
                    ),
                  ],
                )).toList(),
              ],
            ),
          ],
        ),
      );

      final file = File('$exportDir/$fileName');
      await file.writeAsBytes(await pdf.save());
      
      // 分享文件
      await shareFile(file.path, '$type报表 - $period');
      
      return file.path;
    } catch (e) {
      print('错误导出PDF失败: $e');
      Get.snackbar('错误', '导出PDF失败: $e');
      return null;
    }
  }

  /// 导出为Excel
  Future<String?> exportToExcel(List<Map<String, dynamic>> data, String type, String period) async {
    try {
      if (!await requestStoragePermission()) {
        Get.snackbar('错误', '需要存储权限才能导出文件');
        return null;
      }

      final excel = Excel.createExcel();
      final sheet = excel.sheets.values.first;
      final exportDir = await getExportDirectory();
      final fileName = '${type}_${period}_${DateTime.now().millisecondsSinceEpoch}.xlsx';

      // 添加标题
      sheet.cell(CellIndex.indexByColumnRow(columnIndex: 0, rowIndex: 0)).value = '$type报表 - $period';
      
      // 添加表头
      sheet.cell(CellIndex.indexByColumnRow(columnIndex: 0, rowIndex: 2)).value = '分类';
      sheet.cell(CellIndex.indexByColumnRow(columnIndex: 1, rowIndex: 2)).value = '金额';
      sheet.cell(CellIndex.indexByColumnRow(columnIndex: 2, rowIndex: 2)).value = '占比';

      // 添加数据
      for (var i = 0; i < data.length; i++) {
        final item = data[i];
        sheet.cell(CellIndex.indexByColumnRow(columnIndex: 0, rowIndex: i + 3)).value = item['name'];
        sheet.cell(CellIndex.indexByColumnRow(columnIndex: 1, rowIndex: i + 3)).value = item['amount'];
        sheet.cell(CellIndex.indexByColumnRow(columnIndex: 2, rowIndex: i + 3)).value = '${item['percent']}%';
      }

      final file = File('$exportDir/$fileName');
      await file.writeAsBytes(excel.encode()!);
      
      // 分享文件
      await shareFile(file.path, '$type报表 - $period');
      
      return file.path;
    } catch (e) {
      print('错误导出Excel失败: $e');
      Get.snackbar('错误', '导出Excel失败: $e');
      return null;
    }
  }
} 